/*
 * Copyright 2012 Marsrutai.lt
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package lt.marsrutai.mobile.android.manager;

import java.util.Locale;

import lt.marsrutai.mobile.android.R;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.content.res.Resources;
import android.preference.ListPreference;
import android.preference.Preference;
import android.preference.PreferenceManager;
import android.widget.Toast;

/**
 * Coordinates active language preferences.
 * Use language-values.xml in order to modify supported and default languages.
 * For reference on current codes, look at {@link http://developer.android.com/reference/java/util/Locale.html}.
 *
 * @author Paulius
 *
 */
public class LanguagePreferenceManager extends AppPreferenceManager
    implements OnSharedPreferenceChangeListener {

    public final static String KEY_GUI_LANGUAGE = "gui_language";
    private final static Logger logger = LoggerFactory.getLogger("LanguagePreferenceManager");

    public LanguagePreferenceManager(Activity activity, Object caller) {
        super(activity, caller);
    }

    /**
     * Registers listeners for language preferences
     */
    public void registerListeners(SharedPreferences sharedPreferences) {
        sharedPreferences.registerOnSharedPreferenceChangeListener(this);
    }

    /**
     * Unregisters listeners for language preferences
     */
    public void unregisterListeners(SharedPreferences sharedPreferences) {
        sharedPreferences.unregisterOnSharedPreferenceChangeListener(this);
    }

    private static String resolveActiveAppLanguageCode(Context context) {
        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);

        return preferences.getString(KEY_GUI_LANGUAGE, "");
    }

    /**
     * Depending on the active system locale and supported languages decides
     * which locale should the app use to display its GUI.
     *
     * @return locale that the app should use for its GUI.
     */
    public static Locale resolveActiveAppLocale(Context context) {
        String userLanguageCode = resolveActiveAppLanguageCode(context);

        if ("".equals(userLanguageCode)) {
            return Locale.getDefault();
        }

        return new Locale(userLanguageCode);
    }

    private String getLanguageName(String languageCode) {
        Resources appResources = activity.getResources();

        String[] supportedLanguageCodes = appResources.getStringArray(R.array.application_language_values);
        String[] supportedLanguageNames = appResources.getStringArray(R.array.application_language_names);

        for (int i = 0; i < supportedLanguageCodes.length; i++) {
            if (supportedLanguageCodes[i].equals(languageCode)) {
                return supportedLanguageNames[i];
            }
        }

        logger.error(String.format("No matching language name was found for language code %s.", languageCode));
        return null;
    }

    /**
     * Updates the summary of the current application language preference
     */
    public void updateCurrentAppLanguageSummary() {
        String guiLanguageName = getLanguageName(resolveActiveAppLanguageCode(activity));

        Preference languagePreference = findPreference(KEY_GUI_LANGUAGE);

        languagePreference.setSummary(guiLanguageName);
    }

    public void updateCurrentSelection() {
        ListPreference languagePreference = (ListPreference)findPreference(KEY_GUI_LANGUAGE);

        String prefValue = languagePreference.getValue();
        if (prefValue == null) {
            languagePreference.setValueIndex(0);
        }
    }

    @Override
    public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
        updateCurrentAppLanguageSummary();

        Toast.makeText(activity, R.string.language_preferences_app_requires_restart, Toast.LENGTH_LONG).show();
    }
}
